﻿// <copyright file="HomeController.cs" company="Clever Software">
// Copyright (c) 2013, 2014 All Right Reserved, http://www.cleversoftware.by
//
// This source is subject to the Microsoft Permissive License.
// Please see the License.txt file for more information.
// All other rights reserved.
//
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY 
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// </copyright>
// <author>Clever Software</author>
// <email>info@cleversoftware.by</email>
// <date>2014-02-04</date> 
// <summary>CleverCMS source code</summary>

namespace CleverCMS.Web.Controllers
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using System.Web.Helpers;

    using CleverCMS.Core.Attributes;
    using CleverCMS.Core.Services;
    using CleverCMS.Cms.Services;
    using CleverCMS.Cms.Services.ViewModels;
    using CleverCMS.Cms.Data.Entities;

    [SupportSkin]
    public class HomeController : CleverCmsController
    {
        private readonly LoggingService m_log;
        private readonly PageService m_pageService;

        public HomeController(PageService pageService,
                              LoggingService log)
        {
            m_pageService = pageService;
            m_log = log;
        }

        public ActionResult Default()
        {
            var defaultPage = m_pageService.LoadDefault();
            return ShowPage("StartPage", new PageEntryModel(defaultPage));
        }

        [OutputCache(CacheProfile = "Page")]
        public ActionResult Content(int id, string name)
        {

            var page = string.IsNullOrEmpty(name) ? m_pageService.GetByUrl("main") : m_pageService.GetByUrl(name);
            if (page != null && page.StatusId == (int)StatusCode.Published)
            {
                var model = new PageEntryModel
                {
                    Page = page,
                    Rating = ConvertToRatingViewModel(m_pageService.GetRating(page.Id).ToList(), page.Id),
                    HasComments = page.HasComments,
                    PageComments = new PageCommentsViewModel
                                        {
                                            Id = page.Id,
                                            Comments = m_pageService.GetEntryComments(page.Id)
                                        }
                };

                m_pageService.AddViewCount(page);
                return ShowPage(model);

            }
            else
            {
                throw new HttpException(404, "Not Found");
            }

        }

        private ActionResult ShowPage(PageEntryModel entry)
        {
            return View("Index", entry);
        }

        private ActionResult ShowPage(string page, PageEntryModel entry)
        {
            return View(page, entry);
        }

        public PartialViewResult LastPages()
        {
            IEnumerable<CmsPage> lastCreated = m_pageService.LoadLastCreated();
            return PartialView("LastPages", lastCreated);
        }

        public ViewResult Tag(string tag)
        {
            IEnumerable<CmsPage> matchedPages = m_pageService.GetPagesWithTag(tag);
            return View(new TagViewModel { Pages = matchedPages, Tag = tag });
        }

        [OutputCache(Duration = 600)]
        public string Version()
        {
            string version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
            return version;
        }

        public ActionResult ContactUs()
        {
            return View();
        }

        [HttpPost]
        public bool SendMail(string name, string email, string phone, string message)
        {
            bool result = true;
            try
            {
                WebMail.Send("info@uml.by", "Обратная связь с сайта", string.Format("имя: {0} телефон: {1} сообщение: {2} емэйл: {3}", name, phone, message, email), "info@uml.by");
            }
            catch (Exception ex)
            {
                result = false;
            }

            return result;
        }

        // TODO: Rework Rating converters
        #region Rating converters for page
        private static PageRatingViewModel ConvertToRatingViewModel(List<CmsRating> ratings, int objectId)
        {
            if (ratings != null && ratings.Any())
            {
                int count = ratings.Count();
                double avg = ratings.Sum(cmsRating => cmsRating.Rating) / count;
                return new PageRatingViewModel { AverageRating = ConvertDoubleToFixed(avg), TotalRaters = count, IsPage = true, Id = objectId };
            }
            else
            {
                return new PageRatingViewModel { AverageRating = 0, TotalRaters = 0, IsPage = true, Id = objectId };
            }
        }
        private static double ConvertDoubleToFixed(double from)
        {
            double cel = Math.Truncate(from);
            double ost = from - cel;
            double del = Math.Truncate(ost / 0.25);
            return cel + (del + (ost % 0.25 > 0.125 ? 1 : 0)) * 0.25;
        }
        #endregion
    }
}